<template>

  <div class="app-container" >

    <div  class="filter-container">
      <el-input  style="width: 200px;"   v-model="query.serialNumber" placeholder="序列号" class="filter-item"  ></el-input>
      <el-select  class="filter-item" v-model="query.type" placeholder="类型" >
        <el-option label="序列号类型" value="all"></el-option>
        <el-option label="D" value="D"></el-option>
        <el-option label="Z" value="Z"></el-option>
      </el-select>
      <el-select  class="filter-item" v-model="query.isBinding" placeholder="是否绑定" >
        <el-option label="是否绑定" value="all"></el-option>
        <el-option label="是" value="1"></el-option>
        <el-option label="否" value="2"></el-option>
      </el-select>
      <el-select  class="filter-item" v-model="query.status" placeholder="是否送出" >
        <el-option label="是否送出" value="all"></el-option>
        <el-option label="是" value="1"></el-option>
        <el-option label="否" value="2"></el-option>
      </el-select>


      <el-date-picker class="filter-item"
        v-model="query.activeTime"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="激活时间"
        end-placeholder="激活时间"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        >
      </el-date-picker>
      <el-date-picker class="filter-item"
        v-model="query.createdAt"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="创建时间"
        end-placeholder="创建时间"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        >
      </el-date-picker>

      <!-- <el-date-picker class="filter-item"
        v-model="query.activeTime"
        type="datetime"
        placeholder="激活时间"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      >
      </el-date-picker> -->
      <!-- <el-date-picker class="filter-item"
        v-model="query.createdAt"
        type="datetime"
        placeholder="创建时间"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
      >
      </el-date-picker> -->
      <el-button @click="getRecords" type="primary" class="filter-item">查询</el-button>
			<el-button @click="reload" type="danger" class="filter-item">刷新</el-button>
			<el-button @click="exportXls" class="filter-item">导出</el-button>

      <el-popconfirm style="margin-left: 5px;"
            confirm-button-text='是的'
            cancel-button-text='再等等'
            icon="el-icon-info"
            icon-color="red"
            title="确定已经送出了吗？"
            @onConfirm="batchSend"
          >
          <el-button type="success"  slot="reference" class="filter-item">批量送出</el-button>
        </el-popconfirm>


			<!-- <el-button @click="getRecords"  class="filter-item">导出</el-button> -->


      <!-- <el-input  style="width: 80px;margin-left: 100px;"   v-model="createSerialNumberCount" placeholder="序列号个数" class="filter-item"  ></el-input> -->
      <el-select style="margin-left: 5px;" class="filter-item" v-model="type" placeholder="类型" >
        <el-option label="D" value="D"></el-option>
        <el-option label="Z" value="Z"></el-option>
      </el-select>
      <el-button @click="openAddDialog" type="primary" class="filter-item">预览序列号</el-button>

    </div>

    <el-table v-loading="listLoading"	:data="list"	element-loading-text="Loading"	border	fit	highlight-current-row @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="45" />
			<!-- <el-table-column type="index" label="序列" width="50" /> -->
			<el-table-column prop="id" label="ID" width="50" />
			<el-table-column prop="serial_number" label="序列号" min-width="100" />
      <el-table-column prop="created_at" label="创建时间" min-width="160" />
			<el-table-column prop="type" label="类型" min-width="50" />
			<el-table-column prop="status" label="状态" min-width="80" >
        <template slot-scope="scope">
          <el-tag   v-if="scope.row.status==1">已送出</el-tag>
          <el-tag type="danger" v-else>未送出</el-tag>
        </template>
      </el-table-column>
			<el-table-column prop="get_driver_info.name" label="绑定人" min-width="80"  />
			<el-table-column prop="get_user_info.phone" label="手机" min-width="120"  />
			<el-table-column prop="get_driver_info.id_card" label="身份证号" min-width="180"  />
			<el-table-column prop="get_user_info.active_time" label="激活时间" min-width="160"  />
      <el-table-column prop="beizhu" label="备注" min-width="160"  />

			<el-table-column fixed="right" label="操作" min-width="260" >
				<template slot-scope="scope">
          <el-button v-if="scope.row.type=='D' && scope.row.user_id==0 && scope.row.status!=1" size="mini" type="danger" @click="seeForm(scope.row.serial_number)">查看保单</el-button>
          <el-button size="mini" type="primary" @click="addBeizhu(scope.row.id)">添加备注</el-button>
          <el-popconfirm style="margin-left: 5px;" v-if="scope.row.status==2"
            confirm-button-text='是的'
            cancel-button-text='再等等'
            icon="el-icon-info"
            icon-color="red"
            title="确定已经送出了吗？"
            @onConfirm="send(scope.row.id)"
          >
          <el-button   slot="reference" size="mini" >送出</el-button>

        </el-popconfirm>


				</template>
			</el-table-column>
		</el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[10, 20, 100, 200]"
      :page-size="pagination.pageSize"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>

    <el-dialog title="序列号预览" :visible.sync="dialogTableVisible">
      <el-table v-loading="dialogListLoading" :data="generateSerialNumber">
        <el-table-column property="id" label="ID" width="150"></el-table-column>
        <el-table-column property="serial_number" label="序列号" width="150"></el-table-column>
      </el-table>
      <el-button @click="closeAddDialog">取 消</el-button>
      <el-popconfirm title="这确定生成吗？" @onConfirm="createSerialNumber" >
        <el-button slot="reference" type="primary" >确 定</el-button>
      </el-popconfirm>
    </el-dialog>

    <el-dialog width="60%"   :visible.sync="dialogFormVisible">

<!--      <el-input style="width: 200px;margin-bottom: 10px;text-align: center" v-id="isShow" v-model="name" placeholder="姓名" ></el-input>-->
      <div  class="container" id="capture">
        <div class="banner"><img src="./images/jiaxiao_02.jpg" alt=""></div>
        <div class="main-box">
          <div class="table-box">
            <div class="table-item">
              <div class="title-box">
                <div class="item-title">编 号</div>
                <div class="item-title-en">No.</div>
              </div>
              <div class="word-box">{{currentSerialNumber}}</div>

            </div>
            <div class="table-item">
              <div class="title-box">
                <div class="item-title">户 名</div>
                <div class="item-title-en">Acct.Tit.</div>
              </div>

              <div class="word-box">
                <input v-model="name" style="background-color: unset;border: 0px;font-family: SourceHanSansCN-Regular" ></input>
              </div>

            </div>
            <div class="table-item">
              <div class="title-box">
                <div class="item-title">签发日期</div>
                <div class="item-title-en">Date Of Issuance</div>
              </div>
              <div class="word-box">{{ (new Date()).Format('yyyy-MM-dd')}}</div>
            </div>
            <table>
              <thead>
              <tr>
                <th class="title border-right">摘要</th>
                <th>明细</th>
              </tr>
              </thead>
              <tbody>
              <tr>
                <td class="title border-right">待激活</td>
                <td class="des">
                  <div class="des-con">
                    ·驾乘人员人身意外伤害险30万<br />
                    ·驾乘人员意外伤害附加医疗险1万<br />
                    ·驾乘人员意外伤害住院补贴100元/天<br />
                  </div>

                </td>
              </tr>
              </tbody>
            </table>
          </div>
          <div class="agreement box-list">
            <div class="title">
              <div class="line"></div>
              <div class="title-box">
                <div class="title-box-cn">特别约定</div>
                <div class="title-box-en">Special Agreement</div>
              </div>
              <div class="line"></div>
            </div>
            <div class="agreement-con">
              <ul>
                <li>
                  <div class="num">1、</div>
                  <div class="con">本保单被保险人限年龄在18至70周岁的自然人。</div>
                </li>
                <li>
                  <div class="num">2、</div>
                  <div class="con">本保单承保被保险人在驾驶非营运客车期间或保险期间内以乘客身份乘坐非营运客车期间因遭受意外伤害事故导致的身故残疾及意外住院津贴。</div>
                </li>
                <li>
                  <div class="num">3、</div>
                  <div class="con">
                    本保单意外医疗费用指当地社保范围内医疗费用，每次事故扣除100元免赔额后，按100%比例进行给付。意外住院津贴每次事故免赔3天，每次最高给付日数30天，总给付日数180天。
                  </div>
                </li>
                <li>
                  <div class="num">4、</div>
                  <div class="con">
                    本保险适用《国任财产保险股份有限公司驾乘人员人身意外伤害保险条款》、《国任财产保险股份有限公司驾乘人员人身意外伤害保险附加医疗保险条款》、《国任财产保险股份有限公司附加意外伤害住院补贴医疗保险条款》。
                  </div>
                </li>
              </ul>
            </div>
          </div>
<!--          <div class="interests box-list">
            <div class="title">
              <div class="line"></div>
              <div class="title-box">
                <div class="title-box-cn">我的权益</div>
                <div class="title-box-en">My Rights And Interests</div>
              </div>
              <div class="line"></div>
            </div>
            <div class="interests-con">
              <table>
                <tr>
                  <td class="td-title">
                    <div class="word"><span>保障周期</span>:</div>
                  </td>
                  <td class="td-con">12个月</td>
                </tr>
                <tr>
                  <td class="td-title">
                    <div class="word"><span>姓名</span>:</div>
                  </td>
                  <td class="td-con">
                    <div class="person">
                      <div class="name">{{ name }}</div>
                      <div class="idcard">身份证：142725299004204914</div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <td class="td-title">
                    <div class="word"><span>保障明细</span>:</div>
                  </td>
                  <td class="td-con">

                    <div class="des-con">
                      ·驾乘人员人身意外伤害险30万<br />
                      ·驾乘人员意外伤害附加医疗险1万<br />
                      ·驾乘人员意外伤害住院补贴100元/天<br />
                    </div>
                  </td>
                </tr>
              </table>
            </div>
          </div>-->
          <div class="tips">
            <div class="tips-title">温馨提示：</div>
            <div class="tips-des">在动用权益时，可及时联系您的安全出行顾问，或拨打国任保险</div>
            <div class="tips-mobile">客服电话：956030</div>
          </div>

        </div>
        <div class="footer">
          <img src="./images/jiaxiao_05.jpg" alt="">
        </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePicture">下载保单</el-button>
      </div>

    </el-dialog>

  </div>

</template>

<script>


import { myGet } from '@/utils/myRequest';
import html2canvas from 'html2canvas'
const urlLst = "/guard/serial/lst";
const urlGenerate = "/guard/serial/generate";
const urlPreviewGenerate = "/guard/serial/previewGenerate";
const urlExport = '/guard/serial/exportXls';
const urlChangeStatus = '/guard/serial/changeStatus';
const urlAddBeizhu = '/guard/serial/addBeizhu';

Date.prototype.Format = function (fmt) { // author: meizz
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export default {
  data() {
    return {
      listLoading: true,
      dialogListLoading: false,
      dialogFormVisible: false,
      list: [],
      createSerialNumberCount:20,
      type:'D',
      dialogTableVisible:false,
      generateSerialNumber:[],
      currentSerialNumber:'',
      name:'',
      isShow:true,
      selectAll:[],

      query:{
        serialNumber:'',
        type:'all',
        isBinding:"all",
        activeTime:'',
        createdAt:'',
        status:'all',
      },
      pagination:{
        total:0,
        page:1,
        pageSize:20,
			},
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
    };
  },

  mounted(){
    this.getRecords()
  },

  methods:{

    savePicture() {
      if(this.name==''){
        this.$message.error("亲，您还没填写姓名呢！")
        return;
      }
      myGet(urlChangeStatus,{serialNumber:this.currentSerialNumber}).then(res=>{
        if(res.status){

        }
      })

      // 拿到id为'bussiness-card'元素的DOM
      let htmlDom = document.querySelector('#capture');
      // html2canvas()第一个参数为需要被打印的dom元素，第二个参数是html2canvas的一些配置项
      html2canvas(htmlDom, {
        useCORS: true
      }).then((canvas) => {
        let type = 'png';
        // 打印后的imgData','后的是base64数据
        let imgData = canvas.toDataURL(type);

        function base64ToBlob(img) {
        // 拿到格式为base64的图片
        let imgBase64 = imgData.split(';base64,')[1];
        // 照片格式
        let contentType = imgData.split(';base64,')[0].split(':')[1];
        // 解码base64
        let raw = window.atob(imgBase64);
        let rawLength = raw.length;
        // 转为8 位无符号整型数组
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          // 返回i位置的字符Unicode编码
          uInt8Array[i] = raw.charCodeAt(i)
        }
        return new Blob([uInt8Array], { type: contentType });
      }
        // 下载后的文件名
        //let filename = '个人名片' + (new Date()).getTime() + '.' + type;
        let filename = this.currentSerialNumber + '.' + type;
        const blob = base64ToBlob(imgData);
        // 创建一个事件，evt就是被创建的Event对象
        let evt = document.createEvent("HTMLEvents");
        // 初始化一个点击事件
        evt.initEvent("click", true, true);
        // 创建a标签，加上download属性实现下载
        let aLink = document.createElement("a");
        aLink.download = filename;
        aLink.href = URL.createObjectURL(blob);
        aLink.click();
        this.dialogFormVisible = false
        this.name=''
        this.getRecords()
    })
    },

    seeForm(serial_number){
      this.name=''
      this.currentSerialNumber = serial_number
      this.dialogFormVisible = true
    },

    handleSelectionChange(val) {
      this.selectAll = []
      val.forEach(element => {
          this.selectAll.push(element.id)
        });
      },
    batchSend(){

      myGet(urlChangeStatus,{ids:this.selectAll}).then(res=>{
        if(res.status){
          this.$message.success(res.msg)
          this.getRecords()
        }
      })

    },
    send(id){
      myGet(urlChangeStatus,{id}).then(res=>{
        if(res.status){
          this.$message.success(res.msg)
          this.getRecords()
        }
      })
    },

    addBeizhu(id){
      this.$prompt('请输入备注', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {

          myGet(urlAddBeizhu,{id:id,beizhu:value}).then(res=>{
            if(res.status){
              this.$message.success(res.msg)
              this.getRecords()
            }
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
    },

    openAddDialog(){
        this.generateSerialNumber = []
        myGet(urlPreviewGenerate,{count:this.createSerialNumberCount,type:this.type}).then(res=>{
          if(res.status){
            //this.$message.success(res.msg)
            this.generateSerialNumber = res.data.records
          }
        })
        this.dialogTableVisible= true

      },
    closeAddDialog(){
        this.generateSerialNumber = []
        this.dialogListLoading = false
        this.dialogTableVisible= false
      },

    createSerialNumber(){
      this.dialogListLoading = true
      myGet(urlGenerate,{count:this.createSerialNumberCount,type:this.type}).then(res=>{
        this.dialogListLoading = false
        if(res.status){
          this.$message.success(res.msg)
          this.getRecords()
          this.closeAddDialog()
        }
      })
    },

    reload(){
      Object.assign(this.$data.query,this.$options.data().query)
      Object.assign(this.$data.pagination,this.$options.data().pagination)
      this.getRecords()
    },

    getRecords(){
      let params = Object.assign(this.$data.query,this.$data.pagination)
      myGet(urlLst,params).then(res=>{
        this.listLoading = false
        if(res.status){
          this.list = res.data.records;
          this.pagination.total = res.data.total
        }
      })
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.page = 1
      this.getRecords()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.getRecords();
    },
    exportXls(){
      this.listLoading = true
      let link = document.createElement("a");
      //创建一个a标签
      link.style.display = "none";
      //将a标签隐藏
      link.href = urlExport+"?"+this.toParams(this.query);
      //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
      link.setAttribute("download", name);
      // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
      document.body.appendChild(link);
      //将上面创建的a标签加入到body的尾部
      link.click();
      this.listLoading = false
    },

    toParams(param) {
      var result = ""
      for (let name in param) {
          if (typeof param[name] != 'function') {
              result += "&" + name + "=" + encodeURI(param[name]);
          }
      }
      return result.substring(1)
    }
  }


}
</script>

<style >
@import './css/style.css';
/* 使顶部进行吸顶 */
.top {
  position: sticky;
  position: -webkit-sticky;
  top: 0px;
}
/* 表单大小设置 */
.el-dialog {
  margin: 0 auto !important;
  height: 80%;
  overflow: hidden;
}
.el-dialog__body {
  position: absolute;
  left: 0;
  top: 54px;
  bottom: 70px;
  right: 0;
  padding: 0;
  z-index: 1;
  overflow: hidden;
  overflow-y: auto;
}
/**表单 确定和取消 按钮的位置 */
.el-dialog__footer {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
}
/* 表单输入框的大小 */
.el-input {
  /*width: 50%;*/
}

/* 弹出框滚动条 */
/* 设置滚动条的样式 */
/**解决了滚动条之间发生错位的现象 */
::-webkit-scrollbar {
  width: 10px !important;
  height: 10px !important;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb {
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2);
  /* 滚动条的颜色 */
  background-color: #e4e4e4;
}

</style>

